package server;

import classloader.WebAppClassloader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.adapter.Adapter;
import server.adapter.CoyotoAdapter;
import server.connector.Connector;
import server.connector.Endpoint;
import server.connector.ProtocolHandler;
import server.connector.impl.BioEndpoint;
import server.connector.impl.Http11ProtocolHandler;
import server.container.*;
import server.container.impl.*;
import server.domain.ServletInfo.ServletInfo;
import server.util.Help;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static server.util.Help.dotToSplash;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;
    private String appBase = "";
    private String localhost = "";
    private Server server;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/


        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while (true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }


    }

    private void loadConfig() throws FileNotFoundException {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream resourceAsStream =  classLoader.getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document server = saxReader.read(resourceAsStream);
            Element rootElement = server.getRootElement();
            this.server = new StandServer();

            //加载service
            List<Element> servicesList = rootElement.selectNodes("//Service");
            Service []services = new Service[servicesList.size()];
            for (int i = 0; i < servicesList.size(); i++) {
                services[i] = createService(this.server,servicesList.get(i));
            }
            this.server.setServices(services);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
    public void loadServlet() {

        List<ServletInfo> strings = new ArrayList<>();
        try {
            new Help().doScan(appBase, strings);
        } catch (Exception e) {
            e.printStackTrace();
        }


        for (ServletInfo s : strings) {
            InputStream resourceAsStream = null;
            try {
                resourceAsStream = new FileInputStream(s.getFileName());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            SAXReader saxReader = new SAXReader();

            try {
                Document document = saxReader.read(resourceAsStream);
                Element rootElement = document.getRootElement();

                List<Element> selectNodes = rootElement.selectNodes("//servlet");
                for (int i = 0; i < selectNodes.size(); i++) {
                    Element element = selectNodes.get(i);
                    // <servlet-name>lagou</servlet-name>
                    Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                    String servletName = servletnameElement.getStringValue();
                    // <servlet-class>server.LagouServlet</servlet-class>
                    Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                    String servletClass = servletclassElement.getStringValue();


                    // 根据servlet-name的值找到url-pattern
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    // /lagou
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                    servletMap.put(urlPattern, (HttpServlet) Class.forName(s.getParentFilePath() + "/" + dotToSplash(servletClass) + ".java").newInstance());

                }


            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }

    //4.0
    public void starV4() {
        try {
            loadConfig();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        server.init();
        server.start();
    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.starV4();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建Service节点
     *
     * @param server
     * @param element
     * @return
     */
    private Service createService(Server server, Element element) throws FileNotFoundException {
        List<Element> listConnector = element.selectNodes("//Connector");
        List<Element> listEngine = element.selectNodes("//Engine");
        Service service = new StandService();
        for (int i = 0; i < listEngine.size(); i++) {
            Engine engine = createEngine( service,listEngine.get(i));
            service.addEngine(engine);
        }
        service.setServer(server);

        for (int i = 0; i < listConnector.size(); i++) {
            Element elementConnector = listConnector.get(i);
            String port = elementConnector.attributeValue("port");
            Adapter adapter = new CoyotoAdapter();
            Endpoint endpoint = new BioEndpoint(adapter);
            ProtocolHandler protocolHandler = new Http11ProtocolHandler(endpoint);
            Connector connector = new Connector(protocolHandler);
            adapter.setConnector(connector);
            protocolHandler.setConnector(connector);
            endpoint.setProtocolHandler(protocolHandler);
            connector.setPort(Integer.valueOf(port));
            connector.setServer(server);
            connector.setService(service);

            server.addConnector(connector);
        }
        return service;
    }

    /**
     * 创建引擎
     *
     * @param element
     * @return
     */
    private Engine createEngine( Service service,Element element) throws FileNotFoundException {
        List<Element> listHost = element.selectNodes("//Host");
        Engine engine = new StandEngine();
        Host[] hosts = new Host[listHost.size()];
        for (int i = 0; i < listHost.size(); i++) {
            hosts[i] = createHost(engine, listHost.get(i));
        }
        engine.setHosts(hosts);
        return engine;
    }

    /**
     * 创建Host容器
     *
     * @param engine
     * @param element
     * @return
     */
    private Host createHost(Engine engine, Element element) throws FileNotFoundException {
        Host host = new StandHost();
        String name = element.attributeValue("name");
        String appBase = element.attributeValue("appBase");
        host.setName(name);
        host.setAppBase(appBase);
        host.setEngine(engine);

        File baseFile = new File(host.getAppBase());
        File[] files = baseFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            File web = files[i];
            if (web.isDirectory()) {
                // 初始化Context
                Context context = createContext(web);
                host.addContext(context);
            }
        }
        return host;
    }

    /**
     * 创建上下文容器
     *
     * @param web
     * @return
     */
    private Context createContext(File web) throws FileNotFoundException {
        Context context = new StandContext();
        String name = web.getName();
        context.setContextName(name);
        File classPath = new File(web, "/server");
        URL[] urls = new URL[1];
        try {
            urls[0] = classPath.toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        context.setClassloader(new WebAppClassloader(urls));
        // 加载web.xml,并解析出Wapper
        File webXml = new File(web, "/web.xml");
        if (webXml.exists()) {
            createWapper(context, webXml);
        }
        return context;
    }

    private void createWapper(Context context, File webXml) throws FileNotFoundException {
        InputStream inputStream = new FileInputStream(webXml);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");

            for (Element element : selectNodes) {
                Element servletNameEle = (Element) element.selectSingleNode("//servlet-name");
                String servletName = servletNameEle.getStringValue();
                Element servletClsEle = (Element) element.selectSingleNode("//servlet-class");
                String servletClass = servletClsEle.getStringValue();

                //根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                Wapper wapper = new StandWapper();
                wapper.setServletName(servletName);
                wapper.setClassName(servletClass);
                wapper.setUrlPattern(urlPattern);
                wapper.setContext(context);

                context.addWapper(wapper);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}
